<template>
  <div style="display: flex;flex-direction: row;">
    <div style="width:27%;display: flex;margin: 30px 0 40px 0;" :style="{'height':clientHeight-240+'px'}">
      <div style="flex: 2;" class="bgcolor">
        <div style="height: calc(50% - 7.5px);width: 99.5%;">
          <div class="item-text">气象站布图</div>
          <div style="height: calc(100% - 25px);">
            <OLMap v-if="ishowOLMap" @ready="ready" module="mesher" :isTools="false" :isMapCut="false" :isCoord="false" style="height: 100%">
              :isRuler="false"></OLMap>
          </div>
        </div>
        <div style="height: calc(50% - 7.5px)">
          <div class="item-text">气象站列表</div>
          <div style="width: 98%;height: calc(100% - 41px);margin-top: 6px;margin-left: 1%" class="scroll">
            <el-scrollbar class="page-component_scroll">
              <div class="weather">
                <el-table
                        ref="singleTable"
                        @row-click="rowClick"
                        :data="tableData"
                        :border="false"
                        highlight-current-row
                        style="width: calc(100% - 10px);margin: 0 auto">
                  <el-table-column
                          prop="name"
                          label="名称">
                    <template slot-scope="scope">
                      <div :class="scope.row.indexCount && scope.row.onLine ? '':'not-finish'">{{scope.row.name}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                          prop="lon"
                          label="经度">
                    <template slot-scope="scope">
                      <div :class="scope.row.indexCount && scope.row.onLine ? '':'not-finish'">{{scope.row.lon}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                          prop="lat"
                          label="纬度">
                    <template slot-scope="scope">
                      <div :class="scope.row.indexCount && scope.row.onLine ? '':'not-finish'">{{scope.row.lat}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                          prop="indexCount"
                          label="因子数量">
                    <template slot-scope="scope">
                      <div :class="scope.row.indexCount && scope.row.onLine ? '':'not-finish'">{{scope.row.indexCount}}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>
    </div>
    <div style="width: 100%;display: flex;margin: 30px 0 40px 0" :style="{'height':clientHeight-160+'px'}">
      <div id="echartsContainer" style="flex: 5;margin-bottom: 90px;overflow-x: hidden;" class="scroll">
          <div style="display: flex;flex-wrap: wrap;width: 100%;height:100%;">
            <div style="width: calc(23.9%)" class="bgcolor" v-for="(item, i) in weatherStationData" :key="i"
                 :class="[{'marginT-5': i > 3},{'marginL-5': i % 4 !== 0}]">
              <div class="item-text">气象站数据-{{item.display}}</div>
              <div style="position: relative;" :style="{'height':(clientHeight-360) / 2 +'px'}">
                <div :id="'item'+ i"
                     style="width:420px;height: 275px;left: 50%;position: absolute;top: 55%;transform: translate(-50%, -50%);"
                     :class="item.display === '大气温度' || item.display === '降雨量' ||
                     item.display === '土壤温度' || item.display === '蒸发'?'width200':'width100percent'">
                </div>
              </div>
            </div>
          </div>
      </div>
    </div>
  </div>
</template>

<script>
import meteorologicalViewApi from '@/api/Intelligence/meteorological/MeteorologicalViewApi'
import OLMap from '../../../../components/OLMap'
import echarts from 'echarts'

import {Vector as VectorSource} from 'ol/source.js'
import {Vector as VectorLayer} from 'ol/layer.js'
import Feature from 'ol/Feature'
import {Point} from 'ol/geom.js'
import {fromLonLat} from 'ol/proj'
import Style from 'ol/style/Style'
import Icon from 'ol/style/Icon'

import iconMapToWSite from '../../../../assets/img/map/mapIcon/7.png'
import iconMapToWSiteAct from '../../../../assets/img/map/mapIcon/7_active.png'

export default {
  name: 'meteorological',
  components: {OLMap},
  data () {
    return {
      ishowOLMap: false,
      clientHeight: '',
      weatherStationData: [],
      weatherFrom: {
        name: ''
      },
      echartsList: [],
      timer: null,
      weatherStationId: '',
      tableData: [],
      mapObj: null,
      vrSource_WSite: null,
      wsitStyle: null,
      wsitStyleAct: null
    }
  },
  beforeDestroy () {
    clearTimeout(this.timer)
  },
  created () {
    this.getWeatherStationList()
  },
  mounted () {
    this.$nextTick(function () {
      this.ishowOLMap = true
    })
    this.clientHeight = `${document.documentElement.clientHeight}` // 获取浏览器可视区域高度
  },
  methods: {
    ready (obj) {
      this.mapObj = obj
      // 气象站点source
      this.vrSource_WSite = new VectorSource({features: []})
      let vectorLayer = new VectorLayer({
        layerId: 'vrLayer_WSite',
        title: '气象站点',
        zIndex: 5,
        source: this.vrSource_WSite
      })
      this.mapObj.addLayer(vectorLayer)
      this.wsitStyle = new Style({
        image: new Icon(({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: iconMapToWSite
        }))
      })
      this.wsitStyleAct = new Style({
        image: new Icon(({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: iconMapToWSiteAct
        }))
      })
      let place = fromLonLat([108.06105, 24.21694], 'EPSG:4326')
      this.mapObj.getView().animate({
        zoom: 7,
        center: place
      })
    },
    getWeatherStationList () {
      meteorologicalViewApi.getWeatherStationList().then((res) => {
        if (res.status === 200 && res.data.result !== null) {
          var result = res.data.result
          if (result && result.length > 0) {
            this.weatherStationId = result[0].id
            this.tableData = result
            this.getWeatherStationData(result[0].id)
            // 构建gps点位
            for (let i = 0; i < this.tableData.length; i++) {
              let wsit = this.tableData[i]
              let place = fromLonLat([wsit.lon, wsit.lat], 'EPSG:4326')
              let iconFeature = new Feature({
                geometry: new Point(place),
                name: wsit.lon + ',' + wsit.lat,
                population: 4000,
                rainfall: 500
              })
              let iconStyle = this.weatherStationId === wsit.id ? this.wsitStyleAct : this.wsitStyle
              iconFeature.setStyle(iconStyle)
              iconFeature.setId(wsit.id)
              this.vrSource_WSite.addFeature(iconFeature)
            }
            this.mapObj.on('singleclick', this.clickFeature)
          }
        }
      })
    },
    // 单击Featture切换数据
    clickFeature (evt) {
      if (evt.dragging) {
        return
      }
      let feature = this.mapObj.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
        return feature
      })
      if (feature) {
        let row = {}
        let rowId = feature.getId()
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id === rowId) {
            row = this.tableData[i]
            break
          }
        }
        this.rowClick(row)
        this.$refs.singleTable.setCurrentRow(row)
      }
    },

    getWeatherStationData (id) {
      var params = {
        id: id
      }
      meteorologicalViewApi.findRealDataById(params).then((res) => {
        if (res.status === 200 && res.data.result !== null) {
          var result = res.data.result
          this.weatherStationData = result.weathers
          this.echarts()
        }
      })
      this.setTime()
    },
    setTime () {
      if (this.$route.path.indexOf('/meteorologicalView') === -1) {
        return
      }
      let self = this
      this.timer = setTimeout(() => {
        self.getWeatherStationData(this.weatherStationId)
      }, 20000)
    },
    seeHistory () {
      this.$router.push('/intelligence/meteorological/MeteorologicalHistory')
    },
    rowClick (row) {
      if (!row.indexCount || !row.onLine) {
        return false
      }
      clearTimeout(this.timer)
      this.timer = null
      this.weatherStationId = row.id

      let dom = this
      this.vrSource_WSite.forEachFeature(function (feature) {
        if (feature.getId() === row.id) {
          feature.setStyle(dom.wsitStyleAct)
          let place = fromLonLat([row.lon, row.lat], 'EPSG:4326')
          dom.mapObj.getView().animate({
            center: place
          })
        } else {
          feature.setStyle(dom.wsitStyle)
        }
      })
      this.getWeatherStationData(row.id)
    },
    echarts () {
      this.echartsList = []
      this.$nextTick(function () {
        // 基于准备好的dom，初始化echarts实例
        var count = this.weatherStationData.length
        for (var i = 0; i < count; i++) {
          var id = 'item' + i
          let dom = this.$echarts.init(document.getElementById(id))
          if (this.weatherStationData[i].display.indexOf('温度') !== -1 || this.weatherStationData[i].display.indexOf('雨量') !== -1 ||
                    this.weatherStationData[i].display === '蒸发') {
            let xData = this.weatherStationData[i].value + this.weatherStationData[i].unit
            let value = this.weatherStationData[i].value === null ? '无数据' : xData
            dom.setOption({
              yAxis: [{
                /* min: this.weatherStationData[i].minValue,
                                        max: this.weatherStationData[i].maxValue, */
                offset: -147,
                axisTick: {
                  show: true,
                  color: '#fff'
                },
                axisLine: {
                  show: false,
                  lineStyle: {
                    type: 'solid',
                    color: '#fff', // 左边线的颜色
                    width: '1' // 坐标线的宽度
                  }
                },
                axisLabel: {
                  show: true,
                  formatter: function (value, index) {
                    return value
                  },
                  color: '#fff'
                },
                splitLine: {
                  show: false
                  // color:'#fff',
                },
                splitNumber: 5
              }],
              xAxis: [{
                type: 'category',
                data: [value],
                axisTick: {
                  // color:'#fff',
                  show: false
                },
                axisLine: {
                  //  color:'#fff',
                  show: false
                },
                axisLabel: {
                  textStyle: {
                    color: '#fff'
                  }
                }
              }],
              series: [{
                name: ' ',
                type: 'bar',
                barWidth: 40,
                silent: true,
                itemStyle: {
                  normal: {
                    color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                      offset: 0,
                      color: '#3488DB' // 0% 处的颜色
                    }, {
                      offset: 0.6,
                      color: '#00F5FF' // 60% 处的颜色
                    }], false),
                    barBorderRadius: 3 // 柱状角成椭圆形
                  }
                },
                barGap: '-100%',
                data: [this.weatherStationData[i].minValue, this.weatherStationData[i].maxValue]
              }, {
                name: ' ',
                type: 'bar',
                barWidth: 40,
                data: [{
                  value: this.weatherStationData[i].value,
                  itemStyle: {
                    normal: {
                      barBorderRadius: [0, 0, 0, 0],
                      color: {
                        type: 'bar',
                        colorStops: [{
                          offset: 1,
                          color: '#5FC4DE' // 100% 处的颜色
                        }],
                        globalCoord: false // 缺省为 false
                      }
                    }
                  }
                }]
              }]
            })
          } else if (this.weatherStationData[i].display === '风向') {
            dom.setOption({
              series: [
                {
                  name: '',
                  type: 'gauge',
                  center: ['50%', '50%'], // 默认全局居中
                  radius: '90%',
                  min: 0,
                  max: 360,
                  startAngle: 90,
                  endAngle: 449.9,
                  clockwise: false,
                  splitNumber: 8,
                  axisLine: { // 坐标轴线
                    color: 'white',
                    lineStyle: { // 属性lineStyle控制线条样式
                      width: 10,
                      color: [[0.5, '#3A90CF'], [1, '#3EBEEC']]
                    }
                  },
                  axisTick: { // 坐标轴小标记
                    length: 12, // 属性length控制线长
                    lineStyle: { // 属性lineStyle控制线条样式
                      color: '#fff'
                    }
                  },
                  splitLine: { // 分隔线
                    length: 20, // 属性length控制线长
                    lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                      color: '#fff'
                    }
                  },
                  pointer: {
                    width: 5
                  },
                  title: {
                    // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                    // fontWeight: 'bolder',
                    fontSize: 15,
                    color: '#00F6FF'
                  },
                  detail: {
                    // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                    formatter: function (n) {
                      var t = '无数据'
                      var a = n >= 0 && n < 23 || n < 360 && n >= 338 ? t = '北' : n >= 23 && n < 68 ? t = '东北' : n >= 68 && n < 113 ? t = '东' : n >= 113 && n < 158 ? t = '东南' : n >= 158 && n < 203 ? t = '南' : n >= 203 && n < 248 ? t = '西南' : n >= 248 && n < 293 ? t = '西' : n >= 293 && n < 338 && (t = '西北'),
                        t
                      return a
                    },
                    fontWeight: 'bolder',
                    fontSize: 21,
                    color: '#00F6FF'
                  },
                  data: [{
                    value: this.weatherStationData[i].value,
                    name: this.weatherStationData[i].value
                  }]
                }
              ]
            })
          } else {
            dom.setOption({
              series: [
                {
                  name: '',
                  type: 'gauge',
                  z: 3,
                  /* min: this.weatherStationData[i].minValue,
                                             max: this.weatherStationData[i].maxValue, */
                  // splitNumber: 11,
                  radius: '90%',
                  axisLine: { // 坐标轴线
                    lineStyle: { // 属性lineStyle控制线条样式
                      width: 10,
                      color: [[0.5, '#3A90CF'], [1, '#3EBEEC']]
                    }
                  },
                  axisTick: { // 坐标轴小标记
                    length: 10, // 属性length控制线长
                    lineStyle: { // 属性lineStyle控制线条样式
                      color: '#fff'
                    }
                  },
                  splitLine: { // 分隔线
                    length: 15, // 属性length控制线长
                    lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                      color: '#fff'
                    }
                  },
                  title: {
                    // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                    // fontWeight: 'bolder',
                    fontSize: 15,
                    color: '#00F6FF'
                  },
                  detail: {
                    // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                    formatter: function (value) {
                      if (!value) {
                        value = 0
                      }
                      return value
                    },
                    fontWeight: 'bolder',
                    fontSize: 21,
                    color: '#00F6FF'
                  },
                  data: [{
                    value: this.weatherStationData[i].value,
                    name: this.weatherStationData[i].unit
                  }]
                }
              ]
            })
          }
          this.echartsList.push(dom)
        }
      })
    }
  },
  watch: {
    tableData: function () {
      this.$nextTick(function () {
        this.$refs.singleTable.setCurrentRow(this.tableData[0])
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .not-finish{
    color: #97928b;
  }
  .scroll::-webkit-scrollbar {
    width: 5px;
    height: 5px;
    background-color:#fff;
  }
  .scroll::-webkit-scrollbar-track {
    box-shadow: inset 0 0 0px rgba(240, 240, 240, 0.5);
    border-radius: 10px;
    background-color: rgba(240, 240, 240, .5);
  }
  .scroll::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 0px rgba(14,107,183,1);
    background-color: rgba(14,107,183,0.5);
  }
  /deep/ .el-table--scrollable-x .el-table__body-wrapper{
    overflow: auto;
    overflow-x: hidden;
  }
  /deep/ .el-scrollbar {
    height: 100%;
  }

  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
    margin-right: -29px;
  }

  /deep/ .el-select {
    width: 250px;
    height: 40px;
    border: 1px solid #0E6BB7;
    margin: 5px 0 0 80px;
  }

  /deep/ .el-input--suffix .el-input__inner {
    background-color: transparent;
    border: 0;
  }

  /deep/ .el-select-dropdown__list {
    padding: 10px 0 0 0;
  }

  .navItem {
    cursor: pointer;
    display: inline-block;
    margin: 0 15px 0 0px;
    width: 117px;
    height: 50px;
    text-align: center;
    line-height: 50px;
    text-decoration: none;
    border: 1px solid rgba(3, 222, 238, 1);
    color: rgba(0, 255, 230, 1);
    font-size: 1.6rem;

    &.active {
      -webkit-box-shadow: inset 0 0 15px #00f5ff;
      box-shadow: inset 0 0 15px #00f5ff;
    }
  }

  .bgcolor {
    background-color: rgba(18, 49, 142, 0.2);
    border: 1px solid #00ffff;
    border-image: url("../../../../assets/img/item-box.png");
    border-image-slice: 27;
    border-image-width: 27px;
    border-image-repeat: repeat;
    margin: 0 10px 15px 0;
  }

  .item-text {
    width: 94.5%;
    height: 25px;
    background: linear-gradient(90deg, rgba(33, 125, 194, 1), rgba(9, 65, 110, 1), rgba(9, 65, 110, 1));
    font-family: 'Microsoft YaHei';
    font-weight: 400;
    font-size: 15px;
    color: rgba(255, 255, 255, 1);
    margin: 10px 0 0 10px;
    padding: 6px 0 0 7px;
  }

  .width200 {
    width: 100px;
  }

  .width100percent {
    width: 100%;
  }

  .marginT-5 {
    margin-top: 5px;
  }

  .marginL-5 {
    margin-left: 5px;
  }

  .el-table {
    color: #fff;
    font-size: 12px;
    background-color: rgba(0, 0, 0, 0);
    border: 0 solid #fff !important;
  }

</style>
<style>
  .weather .el-table__header-wrapper, .el-table__footer-wrapper {
    background-color: rgba(127, 211, 191, 0.3) !important;
  }

  .weather .el-table th, .weather .el-table td {
    border-bottom: 2px solid rgba(255, 255, 255, 0.08) !important;
  }

  .weather .el-table--striped .el-table__body tr.el-table__row--striped.current-row td,
  .weather .el-table__body tr.current-row > td,
  .weather.el-table__body tr.hover-row.current-row > td,
  .weather.el-table__body tr.hover-row.el-table__row--striped.current-row > td,
  .weather.el-table__body tr.hover-row.el-table__row--striped > td,
  .weather.el-table__body tr.hover-row > td {
    background-color: rgba(250, 250, 250, 0.1) !important;
  }
</style>
